<?php

namespace Library;

use Library\Traits\HasInstance;

/**
 * @method static Response make()
 */
class Response implements \JsonSerializable
{

    private static ?Response $instance = null;

    use HasInstance;

    protected int $code = 200;
    protected array $response = [
        'code'=>200,
        'status'=>1,
        'message'=>"",
        'data'=> null,
    ];

    public function __construct(){
        header('Content-Type: application/json;charset=utf-8;');
    }


    /**
     * @param string $message
     * @param mixed|null $data
     * @param int $code
     * @return $this
     */
    public function success(string $message = "", mixed $data = null, int $code = 200): static
    {
        $this->code = $code;
        $this->response['code'] = $code;
        $this->response['status'] = 1;
        $this->response['message'] = $message;
        $this->response['data'] = $data;
        http_response_code($this->code);
        return $this;
    }

    /**
     * @param string $message
     * @param mixed|null $data
     * @param int $code
     * @return $this
     */
    public function error(string $message = "", mixed $data = null, int $code = 200): static
    {
        $this->code = $code;
        $this->response['code'] = $code;
        $this->response['status'] = 0;
        $this->response['message'] = $message;
        $this->response['data'] = $data;
        http_response_code($this->code);
        return $this;
    }


    /**
     * @param mixed|null $data
     * @param int $code
     * @return $this
     */
    public function result(mixed $data = null, int $code = 200): static
    {
        $this->code = $code;
        $this->response['code'] = $code;
        $this->response['status'] = 1;
        $this->response['data'] = $data;
        http_response_code($this->code);
        return $this;
    }

    /**
     * @return false|string
     */
    public function toString(): bool|string
    {
        return json_encode($this->response, JSON_UNESCAPED_UNICODE);
    }


    /**
     * @return string|bool
     */
    public function jsonSerialize(): string|bool
    {
        return $this->toString();
    }
}